! function () {
  const OFFSET = 5
  let raf = null
  let speed = 2
  let direction = 1
  const scroll = function () {
    const totalHeight /* 页面总高度 */ = document.documentElement.scrollHeight
    const scrollBarHeight /* 滚动条占据高度 */ = document.documentElement.clientHeight
    const scrollBarTop /* 滚动条距顶部距离 */ = document.documentElement.scrollTop
    /* 未滚动到底部 */
    if (totalHeight - scrollBarHeight > scrollBarTop + OFFSET) {
      raf = window.requestAnimationFrame(scroll)
      window.scrollTo(0, scrollBarTop + direction * speed)
    } else if (raf !== null) {
      console.log('到达底部')
      removeRaf()
    }
  }

  const eventCallback = {
    keypress: e => {
      if (e.key === ' ') {
        if (raf === null) {
          scroll()
        } else {
          setTimeout(() => {
            removeRaf()
          }, 200)
        }
      }
      return e.returnValue = false
    },
    keydown: e => {
      if (['ArrowUp', 'ArrowDown'].includes(e.key)) {
        removeRaf()
        if (e.key === 'ArrowUp') {
          /* 上移 */
          direction = -1
        } else {
          /* 下移加速 */
          speed = 3
        }
        scroll()
        return e.returnValue = false
      }
    },
    keyup: e => {
      if (['ArrowUp', 'ArrowDown'].includes(e.key)) {
        removeRaf()
        scroll()
        return e.returnValue = false
      }
    }
  }

  function removeRaf() {
    window.cancelAnimationFrame(raf)
    direction = 1
    speed = 2
    raf = null
  }

  function removeAllEvent() {
    window.removeEventListener('keypress', eventCallback.keypress)
    window.removeEventListener('keydown', eventCallback.keydown)
    window.removeEventListener('keyup', eventCallback.keyup)
  }

  /* 点击【空格】：暂停/滚动 */
  window.addEventListener('keypress', eventCallback.keypress)

  /* 长按：【上】/【下】方向键，加速/减速 */
  window.addEventListener('keydown', eventCallback.keydown)

  /* 按键抬起时，速度恢复 */
  window.addEventListener('keyup', eventCallback.keyup)
}()
